package com.example.chcrm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chcrm.entity.common.OperateRecord;
import com.example.chcrm.entity.common.RandomHelper;
import com.example.chcrm.entity.common.ResponseMsg;
import com.example.chcrm.entity.common.ServletUtils;
import com.example.chcrm.entity.consignor.CustomerInfo;
import com.example.chcrm.entity.consignor.CustomerType;
import com.example.chcrm.entity.employee.EmployeeVo;
import com.example.chcrm.entity.supplier.HighwaySupplierInfo;
import com.example.chcrm.mapper.CustomerInfoMapper;
import com.example.chcrm.mapper.CustomerTypeMapper;
import com.example.chcrm.mapper.HighwaySupplierInfoMapper;
import com.example.chcrm.mapper.OperateRecordMapper;
import com.example.chcrm.service.HighwaySupplierInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author 邹
 * @Date 2025/4/20 23:39
 * @Version 1.0
 */
@Service
public class HighwaySupplierInfoServiceImpl implements HighwaySupplierInfoService {

    @Autowired
    private HighwaySupplierInfoMapper highwaySupplierInfoMapper;
    @Autowired
    private OperateRecordMapper operateRecordMapper;

    @Override
    public ResponseMsg<IPage<HighwaySupplierInfo>> pageList(HighwaySupplierInfo customerInfo, EmployeeVo empVo) {
        QueryWrapper<HighwaySupplierInfo> query = new QueryWrapper<>();
        if(org.apache.commons.lang3.StringUtils.isNotBlank(customerInfo.getName())){
            query.like("name",customerInfo.getName());
            query.like("short_name",customerInfo.getName());
        }
        if(customerInfo.getStatus() != null){
            query.eq("status",customerInfo.getStatus());
        }
        query.eq("is_deleted",0);
        query.orderByDesc("create_time");
        List<HighwaySupplierInfo> list = highwaySupplierInfoMapper.selectList(query);
        ResponseMsg<IPage<HighwaySupplierInfo>> iPageResponseMsg = new ResponseMsg<>();
        Page<HighwaySupplierInfo> page = new Page<>();
        page.setRecords(list);
        page.setTotal(list.size());
        page.setSize(customerInfo.getRows());
        page.setCurrent(customerInfo.getPage());
        iPageResponseMsg.setData(page);
        iPageResponseMsg.success("查询成功");
        return iPageResponseMsg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> add(HighwaySupplierInfo customerInfo, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();

        // 参数校验
        if (StringUtils.isBlank(customerInfo.getName())) {
            msg.fail("供应商名称不能为空");
            return msg;
        }
        if (StringUtils.isBlank(customerInfo.getShortName())) {
            msg.fail("供应商简称不能为空");
            return msg;
        }
        if (StringUtils.isBlank(customerInfo.getAddress())) {
            msg.fail("供应商地址不能为空");
            return msg;
        }
//        }
//        CustomerType customerType = customerTypeMapper.selectById(customerInfo.getTypeId());
//        customerInfo.setTypeName(customerType.getTypeName());
        if (StringUtils.isBlank(customerInfo.getPhone())) {
            msg.fail("联系电话不能为空");
            return msg;
        }

        // 检查委托商名称是否已存在
        Long count = highwaySupplierInfoMapper.selectCount(new QueryWrapper<HighwaySupplierInfo>()
                .eq("name", customerInfo.getName())
                .eq("is_deleted", 0));
        if (count > 0) {
            msg.fail("供应商名称已存在");
            return msg;
        }

        // 设置默认值
        customerInfo.setId(RandomHelper.uuid());
        customerInfo.setIsDeleted(0);
        customerInfo.setCreateTime(new Date());
        customerInfo.setStatus(0); // 默认状态为待审核

        // 保存委托商信息
        int result = highwaySupplierInfoMapper.insert(customerInfo);
        if (result > 0) {
            // 添加操作记录
            OperateRecord operateRecord = new OperateRecord();
            operateRecord.setId(RandomHelper.uuid());
            operateRecord.setOperateType(OperateRecord.OPE_ADD);
            operateRecord.setSourceId(customerInfo.getId());
            operateRecord.setRemark("新增供应商");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            operateRecord.setCreateTime(sdf.format(new Date()));

            if (empVo != null) {
                operateRecord.setOperationId(empVo.getId());
                operateRecord.setOperationName(empVo.getEmpNm());
            }

            operateRecordMapper.insert(operateRecord);
            msg.success("新增成功");
        } else {
            msg.fail("新增失败");
        }
        return msg;
    }

    @Override
    public ResponseMsg<Object> detail(String id) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        HighwaySupplierInfo customerInfo = highwaySupplierInfoMapper.selectById(id);
        if (customerInfo != null) {
            // 查询操作记录
            List<OperateRecord> operateRecords = operateRecordMapper.selectList(new QueryWrapper<OperateRecord>()
                    .eq("sourceId", customerInfo.getId())
                    .orderByDesc("create_time"));
            customerInfo.setOperateRecordList(operateRecords);
        }
        msg.setData(customerInfo);
        msg.success("查询成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> disable(HighwaySupplierInfo essEmployee, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (StringUtils.isBlank(essEmployee.getId())){
            msg.fail("未找到选中公路供应商");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return msg;
        }
        UpdateWrapper updateWrapper=  new UpdateWrapper<HighwaySupplierInfo>();
        String  res ="";
        if (essEmployee.getStatus()==1){
            updateWrapper.set("status",1);
            updateWrapper.eq("id",essEmployee.getId());
            highwaySupplierInfoMapper.update(null,updateWrapper);
            res ="启动合作成功";
        }else if(essEmployee.getStatus()==2){
            updateWrapper.set("status",2);
            updateWrapper.eq("id",essEmployee.getId());
            highwaySupplierInfoMapper.update(null,updateWrapper);
            res ="退出合作成功";
        }else if(essEmployee.getStatus()==0){
//            updateWrapper.set("status",2);
//            updateWrapper.eq("id",essEmployee.getId());
//            customerInfoMapper.update(null,updateWrapper);
            msg.fail("需要审核");
            return msg;
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            msg.fail("本次操作失败");
            return msg;
        }
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ope.setCreateTime(sdf.format(new Date()));
        ope.setOperateType("修改状态");
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        ope.setSourceId(essEmployee.getId());
        operateRecordMapper.insert(ope);
        msg.success(res);
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> update(HighwaySupplierInfo customerInfo, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (StringUtils.isBlank(customerInfo.getId())) {
            msg.fail("未找到要修改的供应商");
            return msg;
        }
        HighwaySupplierInfo newInfo = highwaySupplierInfoMapper.selectOne(
                new QueryWrapper<HighwaySupplierInfo>().eq("name",customerInfo.getName()).or()
                        .eq("short_name",customerInfo.getShortName()));

        if (newInfo !=null){
            msg.fail("修改的供应商名称已存在");
            return msg;
        }

        // 更新数据
        int result = highwaySupplierInfoMapper.updateById(customerInfo);
        if (result > 0) {
            // 添加操作记录
            OperateRecord operateRecord = new OperateRecord();
            operateRecord.setId(RandomHelper.uuid());
            operateRecord.setOperateType(OperateRecord.OPE_UPDATE);
            operateRecord.setSourceId(customerInfo.getId());
            operateRecord.setRemark("修改供应商信息");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            operateRecord.setCreateTime(sdf.format(new Date()));

            if (empVo != null) {
                operateRecord.setOperationId(empVo.getId());
                operateRecord.setOperationName(empVo.getEmpNm());
            }

            operateRecordMapper.insert(operateRecord);
            msg.success("修改成功");
        } else {
            msg.fail("修改失败");
        }
        return msg;
    }

    @Override
    public ResponseMsg<Object> selectAllHighSupplier() {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        QueryWrapper<HighwaySupplierInfo> query = new QueryWrapper<>();
        query.select("id,name");
        query.eq("is_deleted", 0);
        List<Map<String, Object>> essRole = highwaySupplierInfoMapper.selectMaps(query);
        msg.setData(essRole);
        msg.success("查询成功");
        return msg;
    }
}
